<?php

include_once APPLICATION_DIR . "/application/model/PROVIDER_CATEGORY.php";

class Provider_Category extends DataObjects_PROVIDER_CATEGORY
{
	function getList($filter = array(), &$pager=false)
	{
		$provider_category = new Provider_Category();
        $category_Video_provider = new Category_Video_Provider();
        $category_Video_provider->joinAdd(new Category());
		$provider_category->joinAdd($category_Video_provider);
		if (isset($filter['id_provider']) && $filter['id_provider']) {
			$provider_category->ID_PROVIDER = $filter['id_provider'];
		}
        $provider_category->whereAdd("IS_DELETED = ".IS_NOT_DELETED);
		$provider_category->selectAdd();
		$provider_category->selectAdd("PROVIDER_CATEGORY.*, CATEGORY.ID AS CATEGORY_ID, CATEGORY.NAME AS CATEGORY_NAME");
        $provider_category->groupBy("PROVIDER_CATEGORY.ID, CATEGORY.ID");
		$provider_category->orderBy(DRX_StringUtils::getI18nRealValueSql("PROVIDER_CATEGORY.NAME").",".DRX_StringUtils::getI18nRealValueSql("CATEGORY_NAME"));
		if ($pager == true) {
			$pager = new DBPager($provider_category, $filter, true);
		}

		$provider_category->find();
		return $provider_category;
	}

    function getListunMapped($filter = array(), &$pager=false)
	{
		$provider_category = new Provider_Category();
		if (isset($filter['id_provider']) && $filter['id_provider']) {
			$provider_category->ID_PROVIDER = $filter['id_provider'];
		}
        $provider_category->whereAdd("PROVIDER_CATEGORY.ID NOT IN (SELECT ID_PROVIDER_CATEGORY FROM CATEGORY_VIDEO_PROVIDER)");
		$provider_category->selectAdd();
		$provider_category->selectAdd("PROVIDER_CATEGORY.*, 0 AS ID_CATEGORY");
        $provider_category->orderBy(DRX_StringUtils::getI18nRealValueSql("PROVIDER_CATEGORY.NAME"));
		if ($pager == true) {
			$pager = new DBPager($provider_category, $filter, true);
		}

		$provider_category->find();
		return $provider_category;
	}
	function getCategoryList($id_provider = 0)
	{
        $category = new Category();
		$category->whereAdd("IS_DELETED = ".IS_NOT_DELETED);
		$category->orderBy(DRX_StringUtils::getI18nRealValueSql("CATEGORY.NAME"));
		$category->find();

		return $category;
	}
	
	public function isDeleteAble($id = 0,$id_provider = 0)
	{
		$provider_category = new Provider_Category();
		$provider_category->ID = $id;
		$provider_category->ID_PROVIDER = $id_provider;
		$provider_category->find();
		return $provider_category->N > 0;
	}
	
	public function isExistsByName($id_provider = 0, $id = 0, $name= '', $lang_code)
	{
		if ($name == '')
		{
			return false;
		}	
		$provider_category = new Provider_Category();
		if ($id_provider) {
			$provider_category->ID_PROVIDER = $id_provider;
		}
		if ($id) {
			$provider_category->whereAdd("ID <> {$id}");
		}
        if ($lang_code) {
            $slq = " NAME LIKE '%<{$lang_code}>".trim($name)."</{$lang_code}>%'";
        } else {
            $slq = DRX_StringUtils::isI18nSqlCheckStringUnique($name, 'NAME');
        }
		$provider_category->whereAdd($slq);
		$provider_category->find();
		return $provider_category->N > 0;
	}

	public function validateInput($id_categories = array(), $name_arr){
		global $error_msg;

        if (!count($name_arr)) {
            $error_msg->add(_MSG_INVALID_PROVIDER_CATEGORY_NAME);
        } else {
            if (!isset($name_arr[REQ_LANG])) {
                $message = _LB_CATEGORY_NAME._MSG_VALUE_NAME_BY_LANGUAE_MISSING;
                $message = str_replace("[LANGUAGE]", "&lt;en&gt;", $message);
                $error_msg->add($message);
            }
            $name = "";
            foreach($name_arr as $code => $value) {
                $message = _MSG_VALUE_NAME_BY_LANGUAE_INVALID;
                $message = str_replace("[LANGUAGE]", "&lt;$code&gt;", $message);
                if (!textvalid($value))
                {
                    $error_msg->add($message);
                }

                if (self::isExistsByName($this->ID_PROVIDER, $this->ID, $value, $code))
                {
                    $message = _MSG_VALUE_NAME_BY_LANGUAGE_EXISTS;
                    $message = str_replace("[LANGUAGE]", "&lt;$code&gt;", $message);
                    $error_msg->add($message);
                }

                $name .= "<".$code.">".$value."</".$code.">";
            }
            $this->NAME = $name;
        }
		if (!Category::isExistsByIds($id_categories)) {
			$error_msg->add(_MSG_CATEGORY_NOT_EXISTS);
		}
		
		return $error_msg->isNoError();
	}
        
    function importProviderCategoryList($id_provider, $csv_file) {
        // x. Read and process lines in the data file
        $csv = new Read_CSV($csv_file, IMPORT_FILE_SEPARATOR, IMPORT_FILE_ENCLOSURE, IMPORT_FILE_ESCAPOR);
        $i = 0;
        $errors = array();
        $index = 0;
        while (FALSE !== $arr_data = $csv->NextLine()) {
            $index++;
            $error = $this->validateData($id_provider, $arr_data);
            if (!$error) {
                if (!self::isExistsByName($this->ID_PROVIDER, 0, $this->NAME)) {    
                    $this->insert();
                    
                    //Category_Video_Provider::deleteCategoryVideoProvider($this->ID);
            
                    Category_Video_Provider::insertCategoryVideoProvider($this->ID, array($arr_data[0]));
                    
                    $error = _MSG_INSERT_SUCESSED;
                } else {
                    $error = _MSG_CATEGORY_NAME_EXISTS;
                }
            }

            if (!$errors || !in_array($error, $errors)) {
                $errors[$error][]= $index;			
            }
            if (in_array($error, $errors)) {
                $errors[$error][] = $errors[$error].",".$index;
            }
        }

        // x. Close files
        $csv->Finalize();

        // x. Delete the processed file
        unlink($csv_file);
        foreach($errors as $message=>$value) {
           if ($message == _MSG_CATEGORY_NAME_EXISTS || $message == _MSG_INSERT_SUCESSED)  {
               $messages[] = _LB_LINE.' '.implode(', ', $value).': '.$message;
           } else {
               $messages[] = str_replace('[ERROR]', _LB_LINE.' '.implode(', ', $value).': '.$message, ERR_STYLE);
           }
        }
        return _LB_INMPORT_INFO.'<br/>'.implode('<br/>', $messages);
    }
        
    private function validateData($id_provide, $arr_data)
	{
            
            if (count($arr_data) != 2) {
                    return _MSG_MISSING_DATA;
            }

            $this->ID_PROVIDER = $id_provide;
            $this->NAME = $arr_data[1];

            if (!textvalid($this->NAME))
            {
                    return _MSG_INVALID_CATEGORY_NAME;
            }

            if(!DRX_StringUtils::isI18nStringFormat($this->NAME))
            {
                    return _MSG_NAME_WRONG_FORMAT;
            }
            /*
            if (self::isExistsByName(0, $this->NAME, $this->ID_PROVIDER))
            {
                    return _MSG_CATEGORY_NAME_EXISTS;
            }
            */
            $category = new Category();
            if (!$category->get($arr_data[0])) {
                    return _MSG_CATEGORY_NOT_EXISTS;
            }

            return '';
	}
        
    public function validateFile(){
        global $error_msg;
        if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
            $pathinfo = pathinfo($_FILES['file']['name']);
            $fextension = $pathinfo['extension'];
            if ($fextension != 'csv') {
                    $error_msg->add(_MSG_INVALID_FILE);
            }
        } else {
                 $error_msg->add(_MSG_FILE_NOT_EXISTS);
        }

        return $error_msg->isNoError();
	}
}
